<template>
    <view class="content-reservation">
        <view class="header-section">
            <compResSearch class="search" v-model:inputVal="searchValue" placeholderTip="请输入查找的实验室名称" @search="search">
            </compResSearch>
        </view>

        <z-paging class="Zpage" ref="paging" :fixed="false" :auto="true" :bottom-loading="true" use-virtual-list
            @query="onQuery" :show-scrollbar="false">
            <template #cell="{ item, index }">
                <compHistoryListItem :item="item" @click="viewDetail" @refresh="refreshList"></compHistoryListItem>
            </template>
        </z-paging>

        <!-- 背景动画元素 -->
        <view class="circle circle-1"></view>
        <view class="circle circle-2"></view>
        <view class="circle circle-3"></view>
    </view>
</template>

<script lang="ts" setup>
import db from '@/api/database'
import {
    ref,
    nextTick,
    onMounted,
    computed
} from 'vue'
import {
    onShow
} from '@dcloudio/uni-app'
import compResListItem from '@/pages/reservation/comps/comp-res-list-item.vue'
import compResSearch from '@/pages/reservation/comps/comp-res-search.vue'
import compHistoryListItem from '@/pages/reservationHistory/comps/comp-history-list-item.vue'

const props = defineProps({
    item: {
        type: Object,
        default: {},
    },
    historyList: {
        type: Array,
        default: [],
    },
})

const paging = ref(null)
const searchValue = ref('')

onMounted(() => {
    // 确保组件挂载后立即加载数据
    nextTick(() => {
        if (paging.value) paging.value.reload()
    })
})

onShow(() => {
    nextTick(() => {
        if (paging.value) paging.value.reload()
    })
})

async function onQuery(pageNo, pageSize) {
    try {
        const offset = (pageNo - 1) * pageSize;

        const user = uni.getStorageSync('user')

        if (!user || !user._id) {
            console.error('用户未登录或ID不存在')
            uni.showToast({
                title: '请先登录',
                icon: 'none'
            })
            paging.value.complete([])
            return
        }
        const res = await db.collection('yyjl')
            .where({
                personID: user._id,
                sysName: {
                    $regex: searchValue.value
                }
            })
            .orderBy('date', 'desc')  // 按日期字段倒序排序
            .skip(offset)
            .limit(pageSize)
            .get()

        console.log('获取预约历史数据:', res.data)
        paging.value.complete(res.data);
    } catch (error) {
        console.error('查询数据失败:', error);
        paging.value.complete([], false);
    }
}

function search() {
    if (paging.value) paging.value.reload()
}

// 对预约历史列表进行排序
const sortedHistoryList = computed(() => {
    return [...props.historyList].sort((a, b) => {
        // 首先判断状态优先级
        const getStatusPriority = (item) => {
            const now = new Date()
            const [year, month, day] = item.date.split('-').map(Number)
            const reservationDate = new Date(year, month - 1, day)

            // 获取当前时间
            const currentHour = now.getHours()
            const currentMinute = now.getMinutes()
            const currentTime = currentHour + currentMinute / 60

            // 时间段映射
            const timeSlotMap = {
                '1': { start: 8, end: 10 },
                '2': { start: 10, end: 12 },
                '3': { start: 14, end: 16 },
                '4': { start: 16, end: 18 }
            }

            // 判断是否在使用中
            const isInUse = reservationDate.getDate() === now.getDate() &&
                reservationDate.getMonth() === now.getMonth() &&
                reservationDate.getFullYear() === now.getFullYear() &&
                item.time.some(timeSlot => {
                    const slot = timeSlotMap[timeSlot]
                    if (!slot) return false
                    return currentTime >= slot.start && currentTime < slot.end
                })

            // 判断是否已结束
            const isExpired = reservationDate.getDate() < now.getDate() ||
                reservationDate.getMonth() < now.getMonth() ||
                reservationDate.getFullYear() < now.getFullYear() ||
                (reservationDate.getDate() === now.getDate() &&
                    reservationDate.getMonth() === now.getMonth() &&
                    reservationDate.getFullYear() === now.getFullYear() &&
                    currentTime >= timeSlotMap[Math.max(...item.time)].end)

            if (isInUse) return 0  // 使用中优先级最高
            if (isExpired) return 2  // 已结束优先级最低
            return 3  // 已预约优先级中等
        }

        const priorityA = getStatusPriority(a)
        const priorityB = getStatusPriority(b)

        // 如果状态优先级不同，按优先级排序
        if (priorityA !== priorityB) {
            return priorityA - priorityB
        }

        // 如果状态优先级相同，按日期排序
        const dateA = new Date(a.date)
        const dateB = new Date(b.date)
        return dateA - dateB
    })
})

// 刷新列表
function refreshList() {
    if (paging.value) {
        paging.value.reload()
    }
}

</script>

<style lang="scss" scoped>
@import "/static/css/iconfont.css";

/* 关键帧动画定义 */
@keyframes pulse {
    0% {
        transform: scale(1);
        opacity: 0.8;
    }

    50% {
        transform: scale(1.05);
        opacity: 0.6;
    }

    100% {
        transform: scale(1);
        opacity: 0.8;
    }
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(20px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.content-reservation {
    width: 100%;
    height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
    position: relative;
    overflow: hidden;
    animation: fadeIn 0.8s ease-out;

    .header-section {
        margin-top: 20px;
        width: 95%;
        border-bottom-right-radius: 15px;
        border-bottom-left-radius: 15px;
        box-shadow: 0 5px 15px rgba(167, 216, 255, 0.3);
        z-index: 2;

        .nav-bar {
            display: flex;
            align-items: center;
            padding: 10px 15px;
            margin-top: 20px;

            .nav-left {
                display: flex;
                align-items: center;
                color: #fff;

                text {
                    margin-left: 5px;
                    font-size: 16px;
                }
            }

            .nav-title {
                flex: 1;
                text-align: center;
                color: #fff;
                font-size: 18px;
                font-weight: 500;
                margin-right: 30px;
            }
        }
    }

    .Zpage {
        flex: 1;
        width: 95%;
        padding: 10px;
        z-index: 1;
        position: relative;
    }

    .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 40px 0;

        image {
            width: 200px;
            height: 200px;
            margin-bottom: 20px;
        }

        text {
            color: #999;
            font-size: 14px;
        }
    }
}

/* 背景动画圆圈 */
.circle {
    position: absolute;
    border-radius: 50%;
    background: linear-gradient(45deg, rgba(34, 196, 255, 0.2), rgba(33, 150, 243, 0.2));
    filter: blur(5px);
    z-index: 0;
}

.circle-1 {
    width: 500rpx;
    height: 500rpx;
    top: -150rpx;
    right: -100rpx;
    animation: pulse 8s infinite ease-in-out;
}

.circle-2 {
    width: 350rpx;
    height: 350rpx;
    bottom: 100rpx;
    left: -100rpx;
    animation: pulse 6s infinite ease-in-out 1s;
}

.circle-3 {
    width: 600rpx;
    height: 600rpx;
    bottom: -300rpx;
    right: 30%;
    animation: pulse 10s infinite ease-in-out 2s;
}
</style>